<?php

namespace App\Http\Controllers\Manager;

use App\Http\Controllers\Controller;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Pay;
use Illuminate\Support\Facades\Auth;
use App\Events\PayEvent;
use App\Models\Pay as PayModel;
use App\Models\Server;
use App\Models\Character;
use App\Helper;
use Illuminate\Support\Facades\Config;
use App\Models\User;
use App\Models\Withdraw;
use App\Models\Account;
use App\Events\PlayerMoneyChangeEvent;
use App\Events\ManagerMoneyChangeEvent;
use App\Models\UserMoneyLog;
use App\Models\Player;

class PayController extends Controller
{
    protected function CheckServer($id){
        $server=Server::find($id);
        $uid=Auth::user()->id;
        if ($server->user_id==$uid){
            return $server;
        }else{
            throw new Exception('无权访问此服务器',401);
        }
    }
	/**
	 * [buyServer 服务端购买页面]
	 * @Author   Wuhaojie
	 * @DateTime 2019-10-24T14:40:04+0800
	 * @return   [view]                   [description]
	 */
    public function buyServer($server_id)
    {
        $server=$this->CheckServer($server_id);
    	return view('manager.buyServer',['server' => $server]);
    }

    public function ajaxBuyServer(Request $request){
        $serverId = $request->input('serverId');
        $server=$this->CheckServer($serverId);

        $time=$request->input('time');

        $user = Auth::user();
        $price=$time * Config::get('conf.serverPrice');
        if ($user->remain_money < $price){
            return JsonResponse::create(['err'=>1,'msg'=>'积分不足,请充值']);
        }
        $user->remain_money -= $price;
        $user->save();
        $time = $time * 2592000;
        if ($server->isExpire()) {
            $server->endTime = date('Y-m-d H:i:s',time() + $time); //已经到期是当前日期加购买时长
        } else {
            $server->endTime = date('Y-m-d H:i:s',strtotime($server->endTime) + $time);
        }
        $server->save();
        event(new ManagerMoneyChangeEvent($user->id,$serverId,0,1,2,$price,0,$user->remain_money,'购买服务器时长'));
        return JsonResponse::create(['err'=>0,'data'=>$server]);
    }

    /**
     * [buyServerDo 发起支付请求]
     * @Author   Wuhaojie
     * @DateTime 2019-10-24T15:24:06+0800
     * @return   [type]                   [description]
     */
    // public function buyServerDo(Request $request)
    // {
    // 	if (!Auth::check()) {
    // 		return back()->with('msg','请先登录');
    //     }
    //     $data = $request->all();
    // 	// 支付请求
    // 	$time = $request->input('time');
    // 	$payWay = $request->input('payWay');
    // 	$type = $request->input('type');
    //     $serverId = $request->input('server_id');
    // 	if (!isset($time) || !isset($payWay) || !isset($type) || !isset($serverId) || !is_numeric($time) || $time <= 0) {
    // 		return back()->with('msg','非法参数');
    // 	}
    // 	$totalPrice = $time * config('conf.serverPrice');
    // 	$orderNum = 'wowB'.time().Auth::id();
    //     // 购买还是续费
    //     $server = Server::find($serverId);
    //     $isExpire = $server->isExpire();
    //     if ($isExpire) {
    //         $prefix = '购买';
    //     } else {
    //         $prefix = '续费';
    //     }
    // 	$subject = $prefix.'WOW服务端时长'.$time.'月';
    //     $purpose = array('time' => $time);
    //     $purpose = json_encode($purpose); //序列化购买目的，方便异步回调逻辑处理
    //     event(new PayEvent(Auth::id(),$serverId,0,$orderNum,$type,$totalPrice,$payWay,0,$subject,$purpose));
    // 	if ($payWay == 2) {
    //         // 支付宝
    // 		$aliPay = $this->aliPayOrder($orderNum,0.01,$subject);
	//     	return $aliPay;
    // 	} elseif ($payWay == 1) {
    //         // 微信支付
    //         $wechatPay = $this->wechatPayOrder($orderNum,0.01,$subject);
    //         $data['qrcode'] = $wechatPay['code_url'];
    //         $data['order_num'] = $orderNum;
    //         $data['type'] = $type;
    //         return view('manager.wxPaySuccess',compact('data'));
    //     }
    // }

    // 调起支付宝支付
    public function aliPayOrder($orderNum,$totalPrice,$subject)
    {
    	$order = [
		    'out_trade_no' => $orderNum,
		    'total_amount' => $totalPrice,
		    'subject' => $subject,
		];
		return Pay::alipay()->web($order);
    }

    // 调起微信支付
    public function wechatPayOrder($orderNum,$totalPrice,$subject)
    {
        $order = [
            'out_trade_no' => $orderNum,                 // 订单号
            'total_fee' => $totalPrice * 100,                 // 订单金额，单位：元
            'body' => $subject,   // 订单商品标题
        ];
        return Pay::wechat()->scan($order);
    }

    /**
     * [aliPayReturnUrl 阿里云同步回调]
     * @Author   Wuhaojie
     * @DateTime 2019-10-25T16:58:55+0800
     * @return   [type]                   [description]
     */
    public function aliPayReturnUrl()
    {
        $data = Pay::alipay()->verify();
        if ($data) {
            // 支付表state为1
            $order_num = $data->out_trade_no;
            $pay = PayModel::where('order_num',$order_num)->first();
//            if ($pay->state==1) return redirect('/')->with('opMsg','非法请求');
            $pay->state = 1;
            $pay->save();
            // 判断类型 1客户购买服务端 2玩家氪金 3转账给客户
            $type = $pay->type;
            switch ($type) {
                case '1': //客户充值回调
                    $msg = '充值成功';
                    return redirect('/manager/profit')->with('msg',$msg);
                    break;
                case '2':
                    $msg = '购买升级服务成功';
                    $prefix = Server::find($pay->server_id)->domain;
                    return redirect('http://'.$prefix.'.'.config('conf.domain').'/user/center')->with('msg',$msg);
                    break;
                case '3': //玩家充值回调
                    $msg = '充值成功';
                    $prefix = Server::find($pay->server_id)->domain;
                    return redirect('http://'.$prefix.'.'.config('conf.domain').'/user/moneyLog')->with('msg',$msg);
                    break;

                default:
                    # code...
                    break;
            }
        }
    }

    /**
     * [aliPayNotifyUrl 支付宝异步回调]
     * @Author   Wuhaojie
     * @DateTime 2019-10-26T09:28:34+0800
     * @return   [type]                   [description]
     */
    public function aliPayNotifyUrl()
    {
        $alipay = Pay::alipay();
        try{
            $data = $alipay->verify();
            if ($data) {
                // 支付表state为1
                $order_num = $data->out_trade_no;
                $pay = PayModel::where('order_num',$order_num)->first();
//                if ($pay->state==1) return redirect('/')->with('opMsg','非法请求');
                $pay->state = 1;
                $pay->save();
                $type = $pay->type;
                switch ($type) {
                    case 1:
                         // 客户充值
                        $manager = User::find($pay->manager_id);
                        $manager->Recharge($pay);
                        break;

                    case 2:
                        $server = Server::find($pay->server_id);
                        // 记录客户营收
                        // $manager = User::find($server->user_id);
                        // $manager->remain_money += $pay->money;
                        // $manager->save();

                        $purpose = json_decode($pay->pay_purpose);
                        Helper::setDataBaseConf('mysql_char',$server,'acore_characters');
                        $character = Character::where('guid',$purpose->guid)->first();
                        $character->level = $purpose->desLevel;
                        $character->save();
                        break;

                    case 3: // 玩家充值
                        $player = Player::where('player_id', $pay->player_id)->where('server_id', $pay->server_id)->first();
                        $player->Recharge($pay);
                        break;

                    default:
                        return redirect('/')->with('opMsg','非法请求');
                        break;
                }
            }
        } catch (\Exception $e) {
            $e->getMessage();
        }

        return $alipay->success();
    }

    /**
    *定时器，检测微信支付状态
    *@author 吴胖胖
    *@return json
    */
    public function checkWechatPay(Request $request)
    {
        $order_num = $request->input('order_num');
        $pay = PayModel::where('order_num',$order_num)->first();
        if ($pay['state'] == 1) {
            return ['code' => 1,'msg' => '支付成功', 'result' => $pay];
        }else{
            return ['code' => 2];
        }
    }

    /**
    *微信支付异步回调
    *@author 吴胖胖
    */
    public function wechatPayNotifyUrl()
    {
        $wechatPay = Pay::wechat();
        try{
            $data = $wechatPay->verify();
            if ($data) {
                // 支付表state为1
                $order_num = $data->out_trade_no;
                $pay = PayModel::where('order_num',$order_num)->first();
                if ($pay->state==1) return redirect('/')->with('opMsg','非法请求');
                $pay->state = 1;
                $pay->save();
                $type = $pay->type;
                switch ($type) {
                    case 1:
                        // 客户充值
                        $manager = User::find($pay->manager_id);
                        $manager->Recharge($pay);
                        break;

                    case 2:
                        $server = Server::find($pay->server_id);
                        // 记录客户营收
                        // $manager = User::find($server->user_id);
                        // $manager->remain_money += $pay->money;
                        // $manager->save();

                        $purpose = json_decode($pay->pay_purpose);
                        Helper::setDataBaseConf('mysql_char',$server,'acore_characters');
                        $character = Character::where('guid',$purpose->guid)->first();
                        $character->level = $purpose->desLevel;
                        $character->save();
                        break;

                    case 3:
                        // 用户充值
                        $player = Player::where('player_id', $pay->player_id)->where('server_id', $pay->server_id)->first();
                        $player->Recharge($pay);
                        break;

                    default:
                        return redirect('/')->with('opMsg','非法请求');
                        break;
                }
            }
        } catch (\Exception $e) {
            $e->getMessage();
        }
        return $wechatPay->success();
    }

    /**
     * [profit 积分记录]
     * @Author   WHJ
     * @DateTime 2019-10-27T17:29:03+0800
     * @return   [type]                   [description]
     */
    public function profit(Request $request)
    {
        if ($request->isMethod('post')) {
            $trade_type = $request->post('trade_type') ?? '';
            $list = UserMoneyLog::when($trade_type, function ($query) use ($trade_type) {
                return $query->where('trade_type',$trade_type);
            })->where('user_id',Auth::id())
            ->orderBy('created_at','desc')->paginate(10);
            return view('manager.profit',compact('list','trade_type'));
        }
        $list = UserMoneyLog::where('user_id',Auth::id())->orderBy('id','desc')->paginate(10);
        return view('manager.profit',compact('list'));
    }

    /**
     * [withdraw 提现页面]
     * @Author   Wuhaojie
     * @DateTime 2019-10-28T15:42:20+0800
     * @return   [type]                   [description]
     */
    public function withdraw()
    {
        //提现记录
        $list = Withdraw::where('user_id',Auth::id())->orderBy('created_at','desc')->paginate(10);
        return view('manager.withdraw',compact('list'));
    }

    /**
     * [withdrawDo 提现动作]
     * @Author   Wuhaojie
     * @DateTime 2019-10-28T16:15:12+0800
     * @param    Request                  $request [description]
     * @return   [type]                            [description]
     */
    public function withdrawDo(Request $request)
    {
        $user = Auth::user();
        $remain_money = $user->remain_money;
        $money = $request->input('money');
        if (!isset($money) || !is_numeric($money)) {
            return back()->with('msg','参数错误');
        }
        if ($money > $remain_money) {
            return back()->with('msg','提现金额大于您账户所剩余的金额');
        }
        $moneyRMB=$money/config('conf.oneRMBToMoney');
        $order_num = 'wowB2B'.time().$user->id;
        $cash_fee = $moneyRMB * config('conf.userWithdrawRatio')/100; //手续费 单位积分
        $real_money = $moneyRMB - $cash_fee; //单位元
        $info = $user->name.'提现'.$moneyRMB.'元';
        $data = [];
        $data['user_id'] = $user->id;
        $data['money'] = $moneyRMB;
        $data['real_money'] = $real_money;
        $data['cash_fee'] = $cash_fee;
        $data['remain_money'] = $remain_money - $moneyRMB*config('conf.oneRMBToMoney');
        $data['order_num'] = $order_num;
        $data['info'] = $info;
        $data['alipay_account'] = $user->alipay_account;
        $data['alipay_name'] = $user->alipay_name;
        $item = Withdraw::create($data);
        if (!$item) {
            return back()->with('msg','服务器繁忙');
        }
        $user->remain_money -= $money;
        $user->save();

        event(new ManagerMoneyChangeEvent($user->id,0,0,2,2,$money,$cash_fee*config('conf.oneRMBToMoney'),$user->remain_money,'提现'));
        // 支付表记录
        // event(new PayEvent(Auth::id(),0,0,$order_num,3,$moneyRMB,0,0,$info,''));
        return back()->with('msg','您的提现请求已发起,待工作人员审核后将发放至您的支付宝账户,请注意查收!');
    }


    public function alipaySave(Request $request)
    {
        $user = Auth::user();
        $remain_money = $user->remain_money;
        $new_alipay_account = $request->input('new_alipay_account');
        $new_alipay_name = $request->input('new_alipay_name');
        if (empty($new_alipay_account) || empty($new_alipay_name)) {
            return back()->with('msg','参数错误');
        }
        $user->alipay_account = $new_alipay_account;
        $user->alipay_name = $new_alipay_name;
        $user->save();
        // 支付表记录
        // event(new PayEvent(Auth::id(),0,0,$order_num,3,$money,0,0,$info,''));
        return back()->with('msg','支付宝信息更新成功');
    }

    /**
     * [recharge 余额充值]
     * @Author   W
     * @DateTime 2020-10-26T20:01:54+0800
     * @return   [type]                   [description]
     */
    public function recharge()
    {
        return view('manager.recharge');
    }

    public function rechargeDo(Request $request)
    {
        $data = $request->all();
        $order_no = 'wowU'.time().Auth::id();
        $subject = "WOW客户充值";
        $money = $data['money'];
        event(new PayEvent(Auth::id(),0,0,$order_no,1,$money,$data['pay_way'],0,$subject,''));
        if ($data['pay_way'] == 1) {
            $wechatPay = $this->wechatPayOrder($order_no,$money,$subject);
            $data['qrcode'] = $wechatPay['code_url'];
            $data['order_num'] = $order_no;
            return view('manager.wxPaySuccess',compact('data'));
        } else {
            return $this->aliPayOrder($order_no,$money,$subject);
        }
    }
}
